package com.ys.service.administration.impl;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.ys.dto.AddDto;
import com.ys.entity.administration.AdmSignetManage;
import com.ys.entity.administration.AdmUseSignetApply;
import com.ys.entity.flow.YspModel;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsDict;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.administration.AdmUseSignetApplyMapper;
import com.ys.service.administration.AdmUseSignetApplyService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

@Service("admUseSignetApplyService")
public class AdmUseSignetApplyServiceImpl implements AdmUseSignetApplyService {

	@Autowired
	private AdmUseSignetApplyMapper admUseSignetApplyMapper;

	@Autowired
	private YspTaskService yspTaskService;


	/**
	 * 新增
	 */
	@Override
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		AdmUseSignetApply admUseSignetApply = JSON.parseObject(JSON.toJSONString(params), AdmUseSignetApply.class);
		admUseSignetApply.setStatus(1);
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			admUseSignetApply.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			R.error("未查询到制单人信息！");
		}

		admUseSignetApply.setEffectStock(0);
		AdmSignetManage admSignetManage = new AdmSignetManage().setCode(admUseSignetApply.getSignetCode()).setSignetStatus(1).queryFirst();
		if(admSignetManage!=null){
			admUseSignetApply.setSignetName(admSignetManage.getSignetName());//印章名称
			admUseSignetApply.setSignetType(admSignetManage.getSignetType());//印章类型
			YsDict ysDict = new YsDict().where("A.DictKey = 'signet_type' AND A.DictValue = '"+admSignetManage.getSignetType()+"'").queryFirst();
			if(ysDict!=null){
				admUseSignetApply.setSignetTypeTxt(ysDict.getDictName());
			}
		}
		//新增
		admUseSignetApplyMapper.insert(admUseSignetApply);

		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, admUseSignetApply.getBid(), createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/administration/webAdmUseSignetApplyController/toEdit?id=" + admUseSignetApply.getId()));
	}

	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params) {
		AdmUseSignetApply admUseSignetApply = JSON.parseObject(JSON.toJSONString(params), AdmUseSignetApply.class);
		// 验证状态
		YsProcInst ysProcInst = new YsProcInst().setBid(admUseSignetApply.getBid()).queryFirst();
		if (ysProcInst == null) {
			return R.error("审批数据不存在，无法编辑");
		} else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("已流转，无法编辑");
		}

		admUseSignetApply.setStatus(1);
		admUseSignetApplyMapper.update(admUseSignetApply);

		return R.ok(AddDto.noAction());
	}


	//删除
	@Override
	@Transactional
	public R del(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		AdmUseSignetApply entity = new AdmUseSignetApply().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		if (!tsUserChange.getUserId().equals(loginUserId) && !"admin".equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		//删除
		admUseSignetApplyMapper.deleteTrue(id);
		//删除流程
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}


	/**
	 * 流转通过
	 */
	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {

		AdmUseSignetApply entity = new AdmUseSignetApply().setId(id).queryFirst();
		Flow f = yspTaskService.flowPass(entity.getBid(), loginUserId);
		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			if (f.getState() == Flow.State.FINISH.value) {
				flowFinish(entity.getBid());
			}
			return R.ok();
		}
	}

	/**
	 * 流转结束
	 */
	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {

		AdmUseSignetApply entity = new AdmUseSignetApply().setBid(bid).queryFirst();
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setAuditingTime(theDate);
		entity.setUpdateTime(theDate);
		admUseSignetApplyMapper.update(entity);
	}


}
